<template>
  <a-modal
      title="修改密码"
      v-model:visible="visible"
      :confirm-loading="confirmLoading"
      :afterClose="remove"
      @ok="handleOk"
  >
    <a-form ref="UpdatePassword" :model="formState" :rules="rules" :labelCol="{'span':5}" :wrapperCol="{'span':18}">
      <a-form-item label="新密码" name="PW">
        <a-input
            type="password"
            v-model:value="formState.password"
            placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item label="确认密码" name="CW">
        <a-input
            type="password"
            v-model:value="formState.checkPW"
            placeholder="请确认密码"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, reactive, ref, toRefs} from "vue"
import {Modal, Form, Input} from "ant-design-vue"
import {useAsync} from "../../../hooks"
import {userUpdatePW} from "@/api/user"

export default defineComponent({
  name: "pw-modal",
  components: {[Modal.name]: Modal,[Form.name]:Form,[Form.Item.name]:Form.Item,[Input.name]:Input},
  props: {
    remove: { // 移除模态框
      type: Function
    },
    fields: {
      type: Object
    },
    callback: {
      type: Function
    }
  },
  setup(props) {
    const UpdatePassword = ref<any>(null)

    const state = reactive({
      visible: true,
      confirmLoading: false,
    })

    const formState = reactive({
      password: "",
      checkPW: "",
    })

    const rules = {
      PW:[
        {
          validator: async (rule,value)=>{
            if(!formState.password){
              return Promise.reject("密码不能为空")
            }
            if(6>formState.password.length||12<formState.password.length){
              return Promise.reject("密码长度应该为6-12位")
            }
            return Promise.resolve()
          }
        }
      ],
      CW:[
        {
          validator: async (rule,value)=>{
            if(formState.password===formState.checkPW){
              return Promise.resolve()
            }
            return Promise.reject("两次输入的密码不一致")
          }
        }
      ]
  }

    const handleOk = () => {
      state.confirmLoading = true
      UpdatePassword.value.validate()
          .then(async res => {
            const params = {
              userid:props.fields?.userid,
              password:formState.password
            }
            const result = await useAsync(userUpdatePW(params), {ref: state, loadingName: 'confirmLoading'})
            props.callback && props.callback()
            state.visible = false
          })
          .catch(err => {
            console.log('error', err)
            state.confirmLoading = false
          })
    }

    return {
      ...toRefs(state),
      handleOk,
      formState,
      rules,
      UpdatePassword,
    }
  }
})
</script>

<style scoped>
</style>
